package com.itrip.log.module.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.itrip.log.module.db.domain.User;
import com.itrip.log.util.Util;

/**
 * Function:登录校验
 *
 * @date:2016年4月26日/下午1:31:32
 * @Author:jeff@aoliday.cao
 * @version:1.0
 */
public class LoginCheckFilter implements Filter {

	@Override
	public void init(FilterConfig cfg) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {
		HttpServletRequest s = (HttpServletRequest) request;
		HttpServletResponse sp = (HttpServletResponse) response;
		String requestURI = s.getRequestURI();
		
		supportCoresss(s, sp);

		if (canSkip(requestURI)) {
			chain.doFilter(request, response);
			return;
		}

		chain.doFilter(request, response);
		
//		if (checkCookie(s)) {
//			chain.doFilter(request, response);
//			return;
//		}
//		request.getRequestDispatcher("/login.html").forward(request, response);
	}

	private boolean canSkip(String requestURI) {
		return requestURI.endsWith("/login.html") || requestURI.contains("/err/") || requestURI.contains("/user/login");
	}

	private void supportCoresss(HttpServletRequest s, HttpServletResponse sp) {
		String header = s.getHeader("Referer");
		String allowDomain = "http://www.itrip.com";
		if (header != null && header.contains("itrip.com"))
			allowDomain = header.substring(0, header.indexOf(".com") + 4);

		sp.addHeader("Access-Control-Allow-Methods", "*");
		sp.addHeader("Access-Control-Allow-Credentials", "true");
		sp.addHeader("Access-Control-Allow-Origin", allowDomain);
		sp.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE");
		sp.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
	}

	private boolean checkCookie(HttpServletRequest s) {
		if (s.getSession().getAttribute("user") != null)
			return true;
		Cookie[] cookies = s.getCookies();
		if (cookies == null)
			return false;
		for (Cookie cookie : cookies) {
			if (cookie.getName().equals("user")) {
				JSONObject json = JSONObject.parseObject(Util.decrypt(cookie.getValue()));
				User user = JSONObject.toJavaObject(json, User.class);
				s.getSession().setAttribute("user", user);
				return true;
			}
		}
		return false;
	}

	@Override
	public void destroy() {

	}

}
